package com.tingyuge.base.jdk.io.nio.charset;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Map;
import java.util.Set;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2022/1/12
 * @description
 */
public class CharsetDemo {
    public static void main(String[] args) throws CharacterCodingException {
        //1.获取 charset对象
        Charset charset = Charset.forName("UTF-8");
        //2.获取编码对象
        CharsetEncoder charsetEncoder = charset.newEncoder();

        //3.创建缓存区
        CharBuffer charBuffer = CharBuffer.allocate(1024);
        charBuffer.put("小刀");
        charBuffer.flip();
        //4.编码

        ByteBuffer byteBuffer = charsetEncoder.encode(charBuffer);
        System.out.println("编码之后的结果: ");
        for (int i = 0; i < byteBuffer.limit(); i++) {
            System.out.println(byteBuffer.get());

        }
        //5.解码
        byteBuffer.flip();
        CharsetDecoder charsetDecoder = charset.newDecoder();
        CharBuffer charBuffer1 = charsetDecoder.decode(byteBuffer);
        System.out.println("解码之后的结果");
        System.out.println(charBuffer1.toString());
        //6.使用GBK 解码
        Charset charset1=Charset.forName( "GBK" );

        byteBuffer.flip();
        CharBuffer charBuffer2 =charset1.decode(byteBuffer);
        System.out.println("使用其他方式进行解码");
        System. out .println(charBuffer2.toString());

    //可用的编码
        Map<String ,Charset> map= Charset.availableCharsets();

        Set<Map.Entry<String,Charset>> set=map.entrySet();
        for (Map.Entry<String,Charset> entry: set) {
            System. out .println(entry.getKey()+ "=" +entry.getValue().toString());

        }
    }
}
